import {FooterToolbar, PageContainer} from "@ant-design/pro-layout";
import UpdateForm, {FormValueType} from "@/pages/TableList/components/UpdateForm";
import {ActionType} from "@ant-design/pro-table";
import ProDescriptions, {ProDescriptionsItemProps} from "@ant-design/pro-descriptions";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons";
import React, {useRef, useState} from "react";
import {Button, message, Modal} from "antd";
import EmployeeInfoForm from "@/components/EmployeeInfoForm";
import {addDriver, fetchAllDriver, rmDriver, updateDriver} from "@/services/Driver";
import ProTable, {ProColumns} from "@ant-design/pro-table/es";
import {Drawer} from "antd/es";
import {FormattedMessage} from "umi";
import {useIntl} from "umi";
import {optMessage} from "@/utils/optMessage";

const handleAdd = async (fields: Domain.Driver) => {
  return await optMessage(async ()=>{
    await addDriver(fields);
  },"添加");
}

const handleUpdate = async (fields: FormValueType) => {
  return await optMessage(async ()=>{
    await updateDriver(fields);
  },"更新");
};


const Driver: React.FC = ()=>{
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<Domain.Driver>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.driver.account"
          defaultMessage="Account"
        />
      ),
      dataIndex: 'account',
      tip: 'The account is the unique key',
      valueType: "textarea",
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.driver.name" defaultMessage="Name" />,
      dataIndex: 'name',
      valueType: 'textarea',
    },
    {
      title: (
        <FormattedMessage
          id="pages.driver.phone"
          defaultMessage="Phone Number"
        />
      ),
      dataIndex: 'phone',
    },
    {
      title: <FormattedMessage id="pages.driver.email" defaultMessage="Email" />,
      dataIndex: 'email',
      valueType: 'textarea'
    },
    {
      title: (
        <FormattedMessage
          id="pages.driver.hireDate"
          defaultMessage="Hire date"
        />
      ),
      sorter: true,
      dataIndex: 'hireDate',
      valueType: 'date',
    },
    {
      title: <FormattedMessage id="pages.driver.birthday" defaultMessage="Birthday" />,
      dataIndex: 'birthday',
      valueType: 'date',
      sorter: true
    },
    {
      title: <FormattedMessage id="pages.driver.status" defaultMessage="Status" />,
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: (
            <FormattedMessage
              id="pages.employee.status.breaking"
              defaultMessage="Breaking"
            />
          ),
          status: 'Default',
        },
        1: {
          text: (
            <FormattedMessage
              id="pages.employee.status.working"
              defaultMessage="Working"
            />
          ),
          status: 'Success',
        },
        2: {
          text: (
            <FormattedMessage
              id="pages.employee.status.not"
              defaultMessage="Not"
            />
          ),
          status: 'Error',
        },
      }
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <EmployeeInfoForm
          // @ts-ignore
          trigger={
            <a key="update">
              <FormattedMessage id="pages.searchTable.update" defaultMessage="Update" />
            </a>
          }
          title="更新司机信息"
          handleUpdate={handleUpdate}
          employee={record}
        />,
        <a key="delete"
           onClick={()=>{
             Modal.confirm({
               title: "是否确认删除用户 "+record.account+" ?",
               icon: <ExclamationCircleOutlined />,
               content: "删除后不可恢复",
               onOk (){
                 rmDriver(record.account)
                   .then(()=>message.success("成功删除"))
                   .catch(()=>message.error("删除失败，请稍后重试"));
               }
             })
           }}>
          <FormattedMessage
            id="pages.searchTable.delete"
            defaultMessage="Delete"
          />
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<Domain.Driver, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.driver.title',
          defaultMessage: 'Driver',
        })}
        actionRef={actionRef}
        rowKey="account"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <EmployeeInfoForm
            // @ts-ignore
            trigger={
              <Button
                type="primary"
                key="primary"
              >
                <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
              </Button>
            }
            title="新增司机"
            handleAdd={handleAdd}
          />,
        ]}
        request={fetchAllDriver}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {/*发生选择时的刷新的页面*/}
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
              &nbsp;&nbsp;
              <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="Total number of service calls"
                />{' '}
                {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)}{' '}
                <FormattedMessage id="pages.searchTable.tenThousand" defaultMessage="万" />
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {

              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
          <Button type="primary">
            <FormattedMessage
              id="pages.searchTable.batchApproval"
              defaultMessage="Batch approval"
            />
          </Button>
        </FooterToolbar>
      )}
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
}

export default Driver;
